import { reactive } from "vue";
import { ResponseCode, type IResponseBody } from "@/common/Responsetypes";

import { useUserStore } from "@/stores/useUserStore";

export default function () {
  const { login } = useUserStore();

  const userInfo = reactive({
    email: "",
    password: "",
  });

  const handleLogin = (fromEL: { validate: () => Promise<void> }) => {
    const page = getCurrentPages();
    // 转发的页面
    const redirectPage =
      page[page.length - 1].$page.fullPath.split("?redirect=")[1];

    fromEL.validate().then(() => {
      uni.showLoading({
        title: "登录中...",
      });

      login(userInfo).then((re: IResponseBody) => {
        if (re.code === ResponseCode.PASS) {
          uni.showToast({
            title: "登录成功",
            duration: 1000,
          });

          // UPDATE 优化，登录成功后，跳转到前一个页面，如果前一个页面没有则跳到首页
          if (redirectPage) {
            uni.reLaunch({
              url: redirectPage,
            });
          } else {
            uni.reLaunch({
              url: "/pages/index/index",
            });
          }
        }
      });
    });
  };

  return {
    userInfo,
    handleLogin,
  };
}
